﻿using DevExpress.XtraCharts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnalysisSystem
{
    public partial class MainForm : Form
    {
        #region 变量
        //指示是否有文件被打开
        private bool isOpenFile = false;
        //打开文件的表格名
        private List<string> tableNameList = new List<string>();
        //选项窗口变量
        private OptionsForm optionsForm;
        private List<string> optionList;
        //平滑选项窗口
        private SmoothOptionForm smoothForm;
        int smoothPoint = -1, smoothTimes = -1;
        //保存文件路径
        private string filePath = string.Empty;
        private string pathExcel = string.Empty;
        private string pathAccess = string.Empty;
        //储存每个tabpage对应的datatable
        private Dictionary<string, DataTable> cacheTable = new Dictionary<string, DataTable>();
        //异步使用的托管
        private delegate void StartProcess();
        private delegate void StopProcess();
        //测试用
        Stopwatch stopwatch = new Stopwatch();
        List<string> relativeList = new List<string>();
        #endregion

        #region 主窗口
        public MainForm()
        {
            InitializeComponent();
            MainFormInitial();
        }
        //主窗口初始化
        private void MainFormInitial()
        {
            filePath = string.Empty;
            pathAccess = string.Empty;
            pathExcel = string.Empty;
            leftFunctionPanel.Controls.Clear();
            categoryTree.Nodes.Clear();
            mainTabControl.TabPages.Clear();            
            cacheTable.Clear();
            leftStatus.Items.Clear();
            tssInfoLabel.Text = string.Empty;
            tssInfoBar.Visible = false;            
            if(!isOpenFile)
            {
                tsmDataMenu.Enabled = false;
                tsmChartMenu.Enabled = false;
            }
        }
        #endregion

        #region 菜单栏部分
        //打开Excel按钮事件
        private void tsmOpenExcelItem_Click(object sender, EventArgs e)
        {
            MainFormInitial();
            filePath = OleDbMethod.GetPath();
            if (filePath != null)
            {
                if (IsExcelFile())
                {
                    isOpenFile = true;
                    Task task = new Task(() => LoadInitial(1));
                    task.Start();
                }
                else MessageBox.Show("打开的文件不是Excel");
            }
        }
        //打开Access按钮事件
        private void tsmOpenAccessItem_Click(object sender, EventArgs e)
        {
            MainFormInitial();
            filePath = OleDbMethod.GetPath();
            if (filePath != null)
            {
                if (IsAccessFile())
                {
                    isOpenFile = true;
                    Task task = new Task(() => LoadInitial(2));
                    task.Start();
                }
                else MessageBox.Show("打开的文件不是Access");
            }
        }
        //导出静态表至Access
        private void tsmExportAccessItem_Click(object sender, EventArgs e)
        {
            string[] staticTableList = { "1-静态", "2-1 日产", "2-2 日产排序", "3-单井汇总", "4-日产汇总" };
            optionsForm = new OptionsForm();
            this.optionList = new List<string>();
            optionsForm.clbOption.Items.Clear();
            optionsForm.clbOption.Items.AddRange(staticTableList);
            optionsForm.btnOptionCertain.Click += BtnOptionCertain_Click;            
            optionsForm.Show();            
        }
        //弹出选项窗口
        private void BtnOptionCertain_Click(object sender, EventArgs e)
        {
            for(int i=0; i<optionsForm.clbOption.Items.Count; i++)
            {
                if (optionsForm.clbOption.GetItemChecked(i))
                    optionList.Add(optionsForm.clbOption.Items[i].ToString());
            }
            if(optionList.Contains("2-1 日产") || optionList.Contains("2-2 日产排序"))
            {
                MessageBox.Show("表内容过大，花费时间较长，请您耐心等待");
            }
            optionsForm.Dispose();
            pathAccess = OleDbMethod.GetPath();
            if (pathAccess != null)
            {
                if (IsAccessFile(pathAccess))
                {
                    Task task = new Task(() => LoadInitial(5, optionList));
                    task.Start();
                }
                else MessageBox.Show("选择的文件不是Access");
            }
        }
        //判断文件是否为Excel
        private bool IsExcelFile(string path = null)
        {
            if (path == null) path = filePath;
            if (path.Contains("xls") || path.Contains("xlsm") || path.Contains("xlsx"))
                return true;
            else return false;
        }
        //判断文件是否为Access
        private bool IsAccessFile(string path = null)
        {
            if (path == null) path = filePath;
            if (path.Contains("accdb"))
                return true;
            else return false;
        }
        #region 异步调用相关方法
        //初始化函数
        private void LoadInitial(int index, List<string> list = null)
        {
            ProgressBarStart();
            if (index == 1) OleDbMethod.ExcelReadInit(filePath);
            if (index == 2) OleDbMethod.AccessReadInit(filePath);
            if (index == 3) OleDbMethod.ExcelToAccessAuto(filePath, null, list);
            if (index == 4) OleDbMethod.ExcelToAccessAuto(filePath, pathAccess, list);
            if (index == 5) OleDbMethod.ExportToAccessFile(pathAccess, list);
            ProgressBarStop();
        }
        //打开文件初始化时操作
        private void ProgressBarStart()
        {
            if (this.InvokeRequired)
            {
                StartProcess startProcess = new StartProcess(ProgressBarStart);
                this.Invoke(startProcess);
            }
            else
            {
                tssInfoBar.Visible = true;
                timer1.Start();
                stopwatch.Restart();
                tssInfoBar.Style = ProgressBarStyle.Marquee;
                tssInfoLabel.Text = string.Format("程序正在进行");
            }
        }
        //打开文件结束时操作
        private void ProgressBarStop()
        {
            if (this.InvokeRequired)
            {
                StopProcess stopProcess = new StopProcess(ProgressBarStop);
                this.Invoke(stopProcess);
            }
            else
            {
                timer1.Stop();
                stopwatch.Stop();
                tssInfoBar.Style = ProgressBarStyle.Blocks;
                tsmDataMenu.Enabled = true;
                tsmChartMenu.Enabled = true;
                tssInfoLabel.Text = string.Format("成功 耗时：{0}s", stopwatch.ElapsedMilliseconds/1000);
                tssInfoBar.Visible = false;
            }
        }
        #endregion
        //查看按钮对应事件
        private void tsmViewItem_Click(object sender, EventArgs e)
        {
            if(filePath != string.Empty)
            {
                List<string> tableName = new List<string>();
                if (IsExcelFile()) tableName = OleDbMethod.GetExcelTableName(filePath);
                if (IsAccessFile()) tableName = OleDbMethod.GetAccessTableName(filePath);
                CreateLeftPanel(tableName);
            }
            else
            {
                MessageBox.Show("当前没有文件被加载");
            }
        }
        //自动转换按钮对应事件
        private void tsmAutoConvertItem_Click(object sender, EventArgs e)
        {
            if (IsExcelFile())
            {
                Task task = new Task(() => LoadInitial(3));
                task.Start();
            }
            else MessageBox.Show("你加载的不是Excel");
        }
        //手动选择转换对应事件
        private void tsmManualConvertItem_Click(object sender, EventArgs e)
        {
            if (IsExcelFile())
            {
                pathAccess = OleDbMethod.GetPath();
                if (pathAccess != null)
                {
                    Task task = new Task(() => LoadInitial(4));
                    task.Start();
                }
            }
            else MessageBox.Show("你加载的不是Excel");
        }
        //新建图按钮
        private void tsmCreateChartItem_Click(object sender, EventArgs e)
        {
            if(mainTabControl.TabPages.Count > 0)
            {
                TabPage tabPage = mainTabControl.SelectedTab;
                string tableName = tabPage.Text;                
                if(tableName.Equals("5-单井日产"))
                {
                    string wellName = categoryTree.SelectedNode.Text;
                    ChartForSingleWellDailyProduction(tableName, wellName);
                    return;
                }
                else if(tableName.Equals("production"))
                {
                    ChartForSingleWellDailyProduction(tableName, "produciton");
                    return;
                }
                else
                {
                    MessageBox.Show("当前表没有需要展示的图表");
                }
            }
            else
            {
                MessageBox.Show("当前没有打开的表需要建图");
            }
        }
        #endregion

        #region 图表部分
        //单井日产的图像
        private void ChartForSingleWellDailyProduction(string tableName, string wellName)
        {
            ChartForm chartForm = new ChartForm();                        
            ChartControl chart1 = CreateChart.CreateNewChart();            
            ChartControl chart2 = CreateChart.CreateNewChart();
            DataTable temple = cacheTable[tableName];
            ChartAddSeries(ref chart1, ref chart2, ref temple);
            TabControl tabControl = new TabControl();
            tabControl.Dock = DockStyle.Fill;
            TabPage tabPage1 = new TabPage(wellName);
            TabPage tabPage2 = new TabPage(wellName);           
            tabPage1.Controls.Add(chart1);
            tabPage2.Controls.Add(chart2);            
            tabControl.TabPages.Add(tabPage1);
            tabControl.TabPages.Add(tabPage2);
            chartForm.Controls.Add(tabControl);
            StartProcess startProcess = new StartProcess(chartForm.Show);
            BeginInvoke(startProcess);
        }
        //添加曲线
        private void ChartAddSeries(ref ChartControl chart1, ref ChartControl chart2, ref DataTable table)
        {
            if (table.TableName.Equals("production"))
            {
                Series series1 = CreateChart.CreateSeries("q(t)", ViewType.Line, table, table.Columns[1].ColumnName, table.Columns[2].ColumnName);
                Series series2 = CreateChart.CreateSeries("平滑值", ViewType.Line, table, table.Columns[1].ColumnName, table.Columns[3].ColumnName);
                Series series3 = CreateChart.CreateSeries("D(t)", ViewType.Line, table, table.Columns[1].ColumnName, table.Columns[4].ColumnName);
                Series series4 = CreateChart.CreateSeries("b(t)", ViewType.Line, table, table.Columns[1].ColumnName, table.Columns[5].ColumnName);
                chart1.Series.Add(series1);
                chart1.Series.Add(series2);
                chart2.Series.Add(series3);
                chart2.Series.Add(series4);
            }
            else
            {
                if (smoothPoint != -1 && smoothTimes != -1)
                {
                    Smooth.SmoothMethod(ref table, "日期", "日产气（万方/天）", smoothPoint, smoothTimes);
                    Series series5 = CreateChart.CreateSeries("平滑日产气", ViewType.Line, table, "日期", "平滑值");
                    chart2.Series.Add(series5);
                }
                Series series1 = CreateChart.CreateSeries("套压(Mpa)", ViewType.Point, table, "日期", "套压（Mpa）");
                Series series2 = CreateChart.CreateSeries("油压(Mpa)", ViewType.Point, table, "日期", "油压（Mpa）");
                Series series3 = CreateChart.CreateSeries("日产水（方/天）", ViewType.Line, table, "日期", "日产水（方/天）");
                Series series4 = CreateChart.CreateSeries("日产气（万方/天）", ViewType.Line, table, "日期", "日产气（万方/天）");
                chart1.Series.Add(series1);
                chart1.Series.Add(series2);
                chart2.Series.Add(series3);
                chart2.Series.Add(series4);
            }
        }
        //SG平滑按钮选项窗口
        private void tsmSGMethodItem_Click(object sender, EventArgs e)
        {
            smoothPoint = -1;
            smoothTimes = -1;
            this.smoothForm = new SmoothOptionForm();
            this.smoothForm.btnSmoothCertain.Click += BtnSmoothCertain_Click;
            this.smoothForm.Show();
        }
        //平滑选项窗口确定按钮事件
        private void BtnSmoothCertain_Click(object sender, EventArgs e)
        {
            smoothPoint = Convert.ToInt32(this.smoothForm.numSmoothPoint.Value);
            smoothTimes = Convert.ToInt32(this.smoothForm.numSmoothTimes.Value);
            if(smoothTimes >= smoothPoint - 1)
            {
                MessageBox.Show("选值不合理，请重新选择");
            }
            else
            {
                MessageBox.Show("平滑值已添加");
            }
            this.smoothForm.Dispose();            
        }
        //查看平滑之后的Db值
        private void tsmDbvalueItem_Click(object sender, EventArgs e)
        {
            string tableName = mainTabControl.SelectedTab.Text;
            if (tableName == "production" && smoothPoint != -1 && smoothTimes != -1)
            {
                DataTable table = cacheTable[tableName];
                Smooth.SmoothMethod(ref table, "Time", "Gas rate", smoothPoint, smoothTimes);
                cacheTable[tableName] = table;
                TabPage tabpage = mainTabControl.SelectedTab;
                mainTabControl.TabPages.Remove(tabpage);
                string tabKeyName = GetPageKeyName(tableName);
                tabpage = CreateTabPage(tableName, tabKeyName);
                mainTabControl.TabPages.Add(tabpage);
            }
            else
            {
                MessageBox.Show("请输入平滑参数");
            }
        }

        #endregion

        #region 左侧栏部分
        //对左侧栏窗口创建
        private void CreateLeftPanel(List<string> leftList)
        {
            AddTableName(ref leftList);
            ToolStripLabel leftLable = new ToolStripLabel();
            leftLable.Text = string.Format("表名");
            leftStatus.Items.Add(leftLable);
            CheckedListBox leftlistBox = CreateCheckedListBox(leftList);
            leftFunctionPanel.Controls.Add(leftlistBox);
        }
        //增加listbox功能选项
        private void AddTableName(ref List<string> list)
        {
            string[] addName = { "2-2 日产排序", "3-单井汇总", "4-日产汇总", "5-单井日产", "6-分类统计", "7-相关性", "8-月产" };
            if(IsAccessFile()) tableNameList = OleDbMethod.GetAccessTableName(filePath);
            if (IsExcelFile()) tableNameList = OleDbMethod.GetExcelTableName(filePath);
            for(int i=0; i<addName.Length; i++)
            {
                if(!IsTableNameExist(addName[i]))
                    list.Add(addName[i]);
            }
        }
        //打开文件中是否有该表
        private bool IsTableNameExist(string name)
        {
            if (tableNameList.Contains(name))
                return true;
            return false;
        }
        //创建listbox函数
        private CheckedListBox CreateCheckedListBox(List<string> leftList)
        {
            CheckedListBox listBox = new CheckedListBox();
            listBox.Dock = DockStyle.Fill;
            listBox.CheckOnClick = true;
            listBox.SelectionMode = SelectionMode.One;
            listBox.ItemCheck += LeftPanelListBox_ItemCheck;
            for(int i=0; i<leftList.Count; i++)
            {
                listBox.Items.Add(leftList[i]);
            }
            return listBox;
        }
        //listbox选中时事件
        private void LeftPanelListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            var obj = sender as CheckedListBox;
            string textName = obj.GetItemText(obj.Items[e.Index]);
            string keyName = string.Format("rootNode");
            //设置为单选
            if (obj.Items.Count > 0)
            {
                for (int i = 0; i < obj.Items.Count; i++)
                {
                    if (i != e.Index)
                        obj.SetItemChecked(i, false);
                }
            }
            if (!obj.GetItemChecked(e.Index))
            {
                CreateTreeNode(keyName, textName);
                //if (textName.Equals("相对时间"))
                //    categoryTree.CheckBoxes = true;
            }
            else
            {
                categoryTree.Nodes.Clear();
            }
        }
        #endregion

        #region DataGridView控件
        //创建gridview函数
        private DataGridView CreateDataGridView(string tableName)
        {
            if (cacheTable[tableName] == null)
            {
                MessageBox.Show("该表为空表");
                return null;
            }
            DataGridView dataGridView = new DataGridView();
            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            dataGridView.Dock = DockStyle.Fill;
            //DataGridViewStyleSet(dataGridView);
            //dataGridView.Size = new Size(this.mainTabControl.ClientSize.Width - 8, this.mainTabControl.ClientSize.Height - 34);
            dataGridView.VirtualMode = true;
            dataGridView.Name = tableName;            
            dataGridView.RowCount = cacheTable[tableName].Rows.Count;
            dataGridView.ColumnCount = cacheTable[tableName].Columns.Count;
            for (int i = 0; i < cacheTable[tableName].Columns.Count; i++)
            {
                string name = cacheTable[tableName].Columns[i].ColumnName;
                dataGridView.Columns[i].Name = name;
                dataGridView.Columns[i].HeaderText = name;
            }
            dataGridView.CellValueNeeded += DataGridView_CellValueNeeded;
            return dataGridView;
        }

        private void DataGridViewStyleSet(in DataGridView dataGridView)
        {
            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            dataGridView.Dock = DockStyle.Fill;
        }
        //datagridview虚拟模式所需函数
        private void DataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            DataGridView dataGridView = sender as DataGridView;
            if (e.RowIndex == dataGridView.RowCount)
                return;
            var value = cacheTable[dataGridView.Name].Rows[e.RowIndex][e.ColumnIndex];
            if (value.GetType().Equals(typeof(DateTime)))
            {
                e.Value = Convert.ToDateTime(value).ToShortDateString();
            }            
            else e.Value = value.ToString();
        }
        #endregion

        #region TabPage控件
        //创建tabpage函数
        private TabPage CreateTabPage(string pageName, string keyName)
        {
            TabPage tabPage = new TabPage();
            tabPage.Text = pageName;
            tabPage.Name = keyName;            
            tabPage.Size = new Size(pageName.Length * 5, 10);
            DataGridView dataGridView = CreateDataGridView(pageName);
            tabPage.Controls.Add(dataGridView);            
            return tabPage;
        }
        //绘制关闭按钮
        private void mainTabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.Graphics.DrawString("x", e.Font, Brushes.Black, e.Bounds.Right - 15, e.Bounds.Top + 4);
            e.Graphics.DrawString(this.mainTabControl.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + 12, e.Bounds.Top + 4);
            e.DrawFocusRectangle();
        }
        //关闭按钮事件
        private void mainTabControl_MouseDown(object sender, MouseEventArgs e)
        {            
            for (int i = 0; i < this.mainTabControl.TabPages.Count; i++)
            {
                Rectangle r = mainTabControl.GetTabRect(i);
                //获取‘x'区域位置坐标
                Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 9, 7);
                if (closeButton.Contains(e.Location))
                {
                    this.mainTabControl.TabPages[i].Controls.Clear();
                    string tableName = mainTabControl.TabPages[i].Text;
                    if (cacheTable.ContainsKey(tableName))
                    {
                        cacheTable.Remove(tableName);
                    }
                    this.mainTabControl.TabPages.RemoveAt(i);                    
                    break;                    
                }
            }
        }
        //创建tabpage时获取用于检索的keyname
        private string GetPageKeyName(string pageName)
        {
            string pageKeyName = string.Format("page{0}", mainTabControl.TabPages.Count);
            for (int i = 0; i < mainTabControl.TabPages.Count; i++)
            {
                if (mainTabControl.TabPages[i].Text.Equals(pageName))
                    pageKeyName = mainTabControl.TabPages[i].Name;
            }
            return pageKeyName;
        }
        #endregion

        #region TreeView控件
        //创建树结点函数
        private void CreateTreeNode(string keyName, string textName)
        {
            TreeNode rootNode = new TreeNode(textName);
            rootNode.Name = keyName;
            TreeNode wellNameNode = new TreeNode();
            if (textName.Equals("2-1 日产"))
            {
                wellNameNode = FillChildNode("井号", 1);
            }
            if (textName.Contains("2-2 日产排序"))
            {
                wellNameNode = FillChildNode("日期", 2);
            }
            if(textName.Equals("5-单井日产"))
            {
                wellNameNode = FillChildNode("井号", 1);
            }
            if(textName.Equals("相对时间"))
            {
                wellNameNode = FillChildNode("井号", 1);
            }
            if(textName.Equals("8-月产"))
            {
                wellNameNode = FillChildNode("井号", 1);
            }
            if(wellNameNode.Nodes.Count > 0) 
                rootNode.Nodes.Add(wellNameNode);
            rootNode.ExpandAll();
            categoryTree.Nodes.Add(rootNode);
            categoryTree.AfterSelect += CategoryTree_AfterSelect;
            categoryTree.MouseDown += CategoryTree_MouseDown;
            categoryTree.MouseEnter += CategoryTree_MouseEnter;
            categoryTree.MouseLeave += CategoryTree_MouseLeave;
            //categoryTree.AfterCheck += CategoryTree_AfterCheck;            
        }
        //按下鼠标事件
        private void CategoryTree_MouseDown(object sender, MouseEventArgs e)
        {
            this.toolTip1.Hide(categoryTree);
        }

        //复选框选中事件（测试用）
        private void CategoryTree_AfterCheck(object sender, TreeViewEventArgs e)
        {
            var tree = sender as TreeView;
            //左侧栏选中的表名，右侧栏TreeView根节点的名字，TabPage的名字
            string tableName = tree.Nodes[0].Text;
            if (e.Node.Checked)
            {
                relativeList.Add(e.Node.Text);
            }
            else
            {
                relativeList.Remove(e.Node.Text);
            }
            DataTable table = RelativeTimeMethod.RelativeTime(relativeList, OleDbMethod.dataTables[1]);
            if (cacheTable.ContainsKey(tableName))
            {
                cacheTable.Remove(tableName);
            }
            cacheTable.Add(tableName, table);
            string pageKeyName = GetPageKeyName(tableName);
            if (mainTabControl.TabPages.ContainsKey(pageKeyName))
            {
                mainTabControl.SelectTab(pageKeyName);
                TabPage tabPage = mainTabControl.SelectedTab;
                tabPage.Controls.Clear();
                //DataGridView dataGridView = CreateDataGridView(tableName);
                //tabPage.Controls.Add(dataGridView);
            }
            else
            {
                TabPage tabPage = CreateTabPage(tableName, pageKeyName);
                mainTabControl.TabPages.Add(tabPage);
                mainTabControl.SelectTab(pageKeyName);
            }
        }
        //鼠标移出控件区域事件
        private void CategoryTree_MouseLeave(object sender, EventArgs e)
        {
            this.toolTip1.Hide(categoryTree);
        }
        //鼠标进入控件区域事件
        private void CategoryTree_MouseEnter(object sender, EventArgs e)
        {
            TreeNode rootNode = new TreeNode();
            if (categoryTree.Nodes.Count > 0)
                rootNode = categoryTree.Nodes[0];
            if (rootNode.Text.Equals("5-单井日产"))
            {
                List<TreeNode> levelNode = new List<TreeNode>();
                if (rootNode.Nodes.Count > 0)
                    levelNode.Add(rootNode.Nodes[0]);
                for (int i = 0; i < levelNode.Count; i++)
                {
                    TreeNode childNode = new TreeNode();
                    for (int j = 0; j < levelNode[i].Nodes.Count; j++)
                    {
                        childNode = levelNode[i].Nodes[j];
                        if (childNode.IsSelected)
                        {
                            Point point = Control.MousePosition;                            
                            List<string> information = SingleWellDailyProduction.ShowWellInformation(childNode.Text);
                            ShowInformationToolTip(childNode.Text, information, point);
                        }
                    }
                }
            }
        }
        //ToolTip展示方法
        private void ShowInformationToolTip(string title, List<string> information, Point point)
        {
            this.toolTip1.ToolTipTitle = title;
            this.toolTip1.IsBalloon = false;
            this.toolTip1.UseFading = false;
            this.toolTip1.InitialDelay = 100;
            this.toolTip1.AutoPopDelay = 10000;            
            string text = string.Empty;            
            for(int i=0; i<information.Count; i++)
            {
                text += information[i] + "\n";
            }
            this.toolTip1.Show(text, categoryTree, point);
        }
        //根据模式不同填充子节点
        private TreeNode FillChildNode(string nodeName, int mode)
        {
            TreeNode treeNode = new TreeNode(nodeName);
            List<string> list = new List<string>();
            if (mode == 1) list = OleDbMethod.GetWellName();
            if (mode == 2) list = OleDbMethod.GetDateAsYearUnit();
            for (int i = 0; i < list.Count; i++)
            {
                string childKeyName = string.Format("Node{0}", i);
                treeNode.Nodes.Add(childKeyName, list[i]);
            }
            return treeNode;
        }
        //treeview选中时事件
        private void CategoryTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var tree = sender as TreeView;
            //左侧栏选中的表名，右侧栏TreeView根节点的名字，TabPage的名字
            string tableName = tree.Nodes[0].Text;            
            //用于分类的名字，可能是井名或日期
            string categoryName = e.Node.Text;
            if (categoryName.Equals("井号")) return;
            if (categoryName.Equals("日期")) return;
            if (categoryName.Equals("5-单井日产")) return;
            if (categoryName.Equals("8-月产")) return;
            //检测缓冲区中对应表名的table是否存在，若存在则删除重新填入
            if (cacheTable.ContainsKey(tableName))
            {
                cacheTable.Remove(tableName);            
            }
            cacheTable.Add(tableName, SelectTable(tableName, categoryName));
            //检测tabcontrol中是否已有该名字的tabpage，若存在则选中该tabpage并更新其中数据
            //若不存在则创建一个新的tabpage
            string pageKeyName = GetPageKeyName(tableName);
            if (mainTabControl.TabPages.ContainsKey(pageKeyName))
            {
                mainTabControl.SelectTab(pageKeyName);
                TabPage tabPage = mainTabControl.SelectedTab;
                if(tabPage.Controls.Count != 0) tabPage.Controls[0].Refresh();         
            }
            else
            {
                TabPage tabPage = CreateTabPage(tableName, pageKeyName);
                tabPage.Refresh();
                mainTabControl.TabPages.Add(tabPage);
                mainTabControl.SelectTab(pageKeyName);
            }
        }
        //根据树结点选择返回对应datatable
        private DataTable SelectTable(string tableName, string categoryName)
        {
            DataTable dataTable = new DataTable();
            if (SelectTableTemplate(categoryName, tableName, out dataTable))
            {
                return dataTable;
            }
            else if (IsTableNameExist(tableName))
            {
                if (IsAccessFile()) dataTable = OleDbMethod.DBAccessToDataTable(filePath, tableName);
                if (IsExcelFile()) dataTable = OleDbMethod.DBExcelToDataTable(filePath, tableName);
            }
            else
            {                
                GetTableWithName(tableName, categoryName, out dataTable);
            }                        
            return dataTable;
        }
        //根据表名返回表
        private bool GetTableWithName(string name, string categoryName, out DataTable dataTable)
        {
            if(name.Equals("3-单井汇总"))
            {
                if (SingleWellSummary.singleWellSumTable.Rows.Count == 0)
                    SingleWellSummary.SingleWellSum();
                dataTable = SingleWellSummary.singleWellSumTable;
                return true;
            }
            if (name.Equals("4-日产汇总"))
            {
                if (DailyProductionSummary.dailyProduction.Rows.Count == 0)
                    DailyProductionSummary.DailyProductionSum();
                dataTable = DailyProductionSummary.dailyProduction;
                return true;
            }
            if (name.Equals("5-单井日产"))
            {
                dataTable = SingleWellDailyProduction.DailyProductionCalculation(categoryName);
                return true;
            }
            if (name.Equals("6-分类统计"))
            {
                if (ClassificationStatistics.statisticsTable.Rows.Count == 0)
                    ClassificationStatistics.Statistics();
                dataTable = ClassificationStatistics.statisticsTable;
                return true;
            }
            if(name.Equals("7-相关性"))
            {
                if (Correlation.CorrelationTable.Rows.Count == 0)
                    Correlation.GetCorrelationTable();
                dataTable = Correlation.CorrelationTable;
                return true;
            }
            if(name.Equals("8-月产"))
            {
                dataTable = MonthProduction.GetMonthProduct(categoryName);
                return true;
            }
            dataTable = null;
            return false;
        }
        //对非计算得到的表，根据TreeView的选择，创建新的表
        private bool SelectTableTemplate(string categoryName, string tableName, out DataTable dataTable)
        {            
            for (int i = 0; i < 3; i++)
            {
                if (OleDbMethod.dataTables[i].TableName.Equals(tableName))
                {
                    DateTime date = new DateTime();
                    if (DateTime.TryParse(categoryName, out date))
                    {
                        var table = from p in OleDbMethod.dataTables[i].AsEnumerable()
                                    where p.Field<DateTime>("日期").Year.Equals(date.Year)
                                    select p;
                        dataTable = table.CopyToDataTable<DataRow>();
                        return true;
                    }
                    else if (tableName.Equals(categoryName))
                    {
                        dataTable = OleDbMethod.dataTables[i];
                        return true;
                    }
                    else
                    {
                        var table = from p in OleDbMethod.dataTables[i].AsEnumerable()
                                    where p.Field<string>("井号").Equals(categoryName)
                                    select p;
                        dataTable = table.CopyToDataTable<DataRow>();
                        return true;
                    }
                }
            }
            dataTable = null;
            return false;
        }
        #endregion
    }
}
